package com.xh.web.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class HttpClientUtil {
    private HttpClientUtil() {
        throw new IllegalStateException("Utility class");
    }
    static int socketTimeout = 300000;// 请求超时时间

    static int connectTimeout = 300000;// 传输超时时间
    // 编码格式。发送编码格式统一用UTF-8
    private static final String ENCODING = "UTF-8";

    /**
     * post 方式请求，application/json; charset=UTF-8
     *
     * @param heads     请求头信息
     * @param jsonParam json格式的参数
     * @return 请求结果
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String postJson(String url, Map<String, String> heads, String jsonParam) throws ClientProtocolException, IOException {

        CloseableHttpClient httpclient = HttpClients.createDefault();

        CloseableHttpResponse resp = null;

        HttpPost post = new HttpPost(url);
        post.addHeader("Content-Type", ContentType.APPLICATION_JSON.toString());
        //  设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(socketTimeout)
                .setConnectTimeout(connectTimeout).build();
        post.setConfig(requestConfig);

        httpPostAddHeader(post,heads);
        if (heads != null && !heads.isEmpty()) {
            for (Map.Entry<String,String> entry : heads.entrySet()) {
                post.addHeader(entry.getKey(),entry.getValue());
            }
        }

        if (StringUtils.isNotBlank(jsonParam)) {
            StringEntity entity = new StringEntity(jsonParam, ContentType.APPLICATION_JSON);
            post.setEntity(entity);
        }

        resp = httpclient.execute(post);

        return EntityUtils.toString(resp.getEntity(), ENCODING);
    }

    private static void httpPostAddHeader(HttpPost post, Map<String, String> heads) {
        if (heads != null && !heads.isEmpty()) {
            for (Map.Entry<String,String> entry : heads.entrySet()) {
                post.addHeader(entry.getKey(),entry.getValue());
            }
        }
    }


    public static String httpPost(String url, Map<String, String> heads, String reqStr) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse resp = null;
        HttpPost post = new HttpPost(url);
        //  设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(socketTimeout)
                .setConnectTimeout(connectTimeout).build();
        post.setConfig(requestConfig);

        //设置头部参数
        httpPostAddHeader(post,heads);
        //请求body参数
        if (StringUtils.isNotBlank(reqStr)) {
            StringEntity entity = new StringEntity(reqStr, ContentType.APPLICATION_JSON);
            post.setEntity(entity);
        }
        resp = httpclient.execute(post);
        return EntityUtils.toString(resp.getEntity(), ENCODING);
    }

    /**
     * httppost请求
     *
     * @param url
     * @param reqStr
     * @return
     * @throws Exception
     * @description 1.头部信息完全是调用者提供
     * 2.超时时间本类提供
     * 3.请求参数调用者提供
     */
    public static byte[] httpPostByte(String url, Map<String, String> heads, String reqStr) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse resp = null;
        HttpPost post = new HttpPost(url);
        //  设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(socketTimeout)
                .setConnectTimeout(connectTimeout).build();
        post.setConfig(requestConfig);

        //设置头部参数
        httpPostAddHeader(post,heads);
        //请求body参数
        if (StringUtils.isNotBlank(reqStr)) {
            StringEntity entity = new StringEntity(reqStr, ContentType.APPLICATION_JSON);
            post.setEntity(entity);
        }
        resp = httpclient.execute(post);
        return EntityUtils.toByteArray(resp.getEntity());
    }

    /**
     * 发送get请求；带请求头和请求参数
     *
     * @param url     请求地址
     * @param headers 请求头集合
     * @param params  请求参数集合
     * @return
     * @throws Exception
     */
    public static String doGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
        // 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建访问的地址
        URIBuilder uriBuilder = new URIBuilder(url);
        if (params != null) {
            Set<Map.Entry<String, String>> entrySet = params.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue());
            }
        }

        // 创建http对象
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        /**
         * setConnectTimeout：设置连接超时时间，单位毫秒。
         * setConnectionRequestTimeout：设置从connect Manager(连接池)获取Connection
         * 超时时间，单位毫秒。这个属性是新加的属性，因为目前版本是可以共享连接池的。
         * setSocketTimeout：请求获取数据的超时时间(即响应时间)，单位毫秒。 如果访问一个接口，多少时间内无法返回数据，就直接放弃此次调用。
         */
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build();
        httpGet.setConfig(requestConfig);

        // 设置请求头
        packageHeader(headers, httpGet);

        // 创建httpResponse对象
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);

        try {
            // 执行请求并获得响应结果
            return getHttpClientResult(httpResponse);
        } finally {
            // 释放资源
            release(httpResponse, httpClient);
        }
    }


    /**
     * 发送post请求；带请求头和请求参数
     *
     * @param url     请求地址
     * @param headers 请求头集合
     * @param params  请求参数集合
     * @return
     * @throws Exception
     */
    public static String doPost(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
        // 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建http对象
        HttpPost httpPost = new HttpPost(url);
        /**
         * setConnectTimeout：设置连接超时时间，单位毫秒。
         * setConnectionRequestTimeout：设置从connect Manager(连接池)获取Connection
         * 超时时间，单位毫秒。这个属性是新加的属性，因为目前版本是可以共享连接池的。
         * setSocketTimeout：请求获取数据的超时时间(即响应时间)，单位毫秒。 如果访问一个接口，多少时间内无法返回数据，就直接放弃此次调用。
         */
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build();
        httpPost.setConfig(requestConfig);
        // 设置请求头
        packageHeader(headers, httpPost);

        // 封装请求参数
        packageParam(params, httpPost);

        // 创建httpResponse对象
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);

        try {
            // 执行请求并获得响应结果
            return getHttpClientResult(httpResponse);
        } finally {
            // 释放资源
            release(httpResponse, httpClient);
        }
    }

    /**
     * Description: 释放资源
     *
     * @param httpResponse
     * @param httpClient
     * @throws IOException
     */
    public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
        // 释放资源
        if (httpResponse != null) {
            httpResponse.close();
        }
        if (httpClient != null) {
            httpClient.close();
        }
    }

    /**
     * Description: 封装请求头
     *
     * @param params
     * @param httpMethod
     */
    public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod) {
        // 封装请求头
        if (params != null) {
            Set<Map.Entry<String, String>> entrySet = params.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                // 设置到请求头到HttpRequestBase对象中
                httpMethod.setHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    /**
     * Description: 封装请求参数
     *
     * @param params
     * @param httpMethod
     * @throws UnsupportedEncodingException
     */
    public static void packageParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod)
            throws UnsupportedEncodingException {
        // 封装请求参数
        if (params != null) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            Set<Map.Entry<String, String>> entrySet = params.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }

            // 设置到请求的http对象中
            httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));
        }
    }

    /**
     * Description: 获得响应结果
     *
     * @param httpResponse
     * @return
     * @throws Exception
     */
    public static String getHttpClientResult(CloseableHttpResponse httpResponse) throws Exception {
        // 执行请求
        String content = "";
        // 获取返回结果
        if (httpResponse != null && httpResponse.getStatusLine() != null) {

            if (httpResponse.getEntity() != null) {
                content = EntityUtils.toString(httpResponse.getEntity(), ENCODING);
            }
            return content;
        }
        return content;
    }
}
